NIO를 이용한 Echo 서버 :: 자바네트워크I/O[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

자바네트워크I/O
[1]
등록일:2008-03-12 10:36:06 (0%)
작성자:
제목:NIO를 이용한 Echo 서버
import  java.net.*;
import  java.nio.*;
import  java.nio.channels.*;
import  java.nio.charset.*;
import  java.util.*;

  

public  class  NioEchoServer
{
  private  int  port  =  9090;
  private  ServerSocketChannel  serverSocketChannel  =  null;
  private  Selector  selector  =  null;
  private  Charset  charset  =  null;
  
  private  Vector  v  =  null;

>더보기

>접기


  public  NioEchoServer()
  {
    try
    {
      charset  =  Charset.forName("EUC-KR");
      selector  =  Selector.open();
      serverSocketChannel  =  ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.socket().bind(new  InetSocketAddress(port));
      serverSocketChannel.register(selector,  SelectionKey.OP_ACCEPT);
      
      v  =  new  Vector();
    }
    catch(Exception  e)
    {
      try
      {
        if(serverSocketChannel  !=  null)
        {
          serverSocketChannel.close();
          serverSocketChannel  =  null;
        }
        if(selector  !=  null)
        {
          selector.close();
          selector  =  null;
        }
      }
      catch(Exception  ex)
      {
        
      }
      e.printStackTrace();
    }
  }
  
  public  void  start()
  {
    while(true)
    {
      try
      {
        selector.select();
        
        Iterator  iter  =  selector.selectedKeys().iterator();
        while(iter.hasNext())
        {
          SelectionKey  key  =  (SelectionKey)iter.next();
          
          if(key.isAcceptable())
          {
            //  accept  처리
            clientAccept(key);
          }
          else  if(key.isReadable())
          {
            //  read  처리
            readMessage(key);
          }
          
          iter.remove();
        }
      }
      catch(Exception  e)
      {
        e.printStackTrace();
      }
    }
  }
  
  private  void  clientAccept(SelectionKey  key)
  {
    SocketChannel  sc  =  null;
    ServerSocketChannel  ssc  =  null;
    
    try
    {
      ssc  =  (ServerSocketChannel)key.channel();
      sc  =  ssc.accept();
      sc.configureBlocking(false);
      sc.register(selector,  SelectionKey.OP_READ);
      
      v.add(sc);
      
      System.out.println(sc.toString()  +  "  클라이언트가  접속을  했습니다.");
    }
    catch(Exception  e)
    {
      if(sc  !=  null)
      {
        try
        {
          sc.close();
          sc  =  null;
        }
        catch(Exception  ex)
        {
          
        }
      }
      e.printStackTrace();
    }
  }
  
  private  void  readMessage(SelectionKey  key)
  {
    ByteBuffer  buffer  =  null;
    SocketChannel  sc  =  null;
    
    try
    {
      buffer  =  ByteBuffer.allocateDirect(1024);
      sc  =  (SocketChannel)key.channel();
      
      sc.read(buffer);
      
      //  모든  클라이언트에게  메시지  전송
      allClientSendMessage(buffer);
      System.out.println(charset.decode(buffer).toString());
      
      buffer.clear();
      buffer  =  null;
    }
    catch(Exception  e)
    {
      try
      {
        v.remove(sc);
        System.out.println(sc.toString()  +  "  클라이언트가  접속을  종료했습니다.");
        
        sc.close();
        sc  =  null;
      }
      catch(Exception  ex)
      {
        
      }
    }
  }
  
  private  void  allClientSendMessage(ByteBuffer  buffer)
  {
    try
    {
      buffer.flip();
      
      Iterator  iter  =  v.iterator();
      
      while(iter.hasNext())
      {
        SocketChannel  sc  =  (SocketChannel)iter.next();
        sc.write(buffer);
        buffer.rewind();
      }
    }
    catch(Exception  e)
    {
      e.printStackTrace();
    }
  }

  public  static  void  main(String[]  args)
  {
    new  NioEchoServer().start();
  }
}
[본문링크] NIO를 이용한 Echo 서버
[1]
코멘트(이글의 트랙백 주소:/cafe/tb_receive.php?no=2526
작성자
비밀번호

 

SSISOCommunity

[이전]

Copyright byCopyright ⓒ2005, SSISO Community All Rights Reserved.